﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Fif.wss;

namespace Fif.text
{
    public class Output
    {       

        private const string Template = "<!DOCTYPE html>\r\n"
            + "<html lang=\"{0}\" xmlns=\"http://www.w3.org/1999/xhtml\">\r\n"
            + "<head>\r\n"
            + "\t<meta charset=\"utf-8\" />\r\n"
            + "\t<title>Search result for {1}</title>\r\n"
            + "</head>\r\n"
            + "<body>\r\n"
            + "<div>Searched text: {1}</div>"
            + "<div>Searched path: {2}</div>"
            + "<hr />"
            + "<table>{3}</table>"
            + "</body>\r\n"
            + "</html>\r\n";

        private string _filePath;

        public Output(string filePath)
        {
            _filePath = filePath;
        }

        public void WriteToFile(string lang, string text, string path, IEnumerable<FileInfo> fileInfos)
        {
            var content = BuildDocument(lang, text, path, fileInfos);
            using (var outfile = new System.IO.StreamWriter(_filePath, false, Encoding.UTF8))
            {
                outfile.Write(content);
            }
        }

        public string BuildDocument(string lang, string text, string path, IEnumerable<FileInfo> fileInfos)
        {
            var table = new StringBuilder();
            foreach(var info in fileInfos)
            {
                table.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", MakeHref(info.Url, info.Name), info.Path);
            }

            var document = string.Format(Template, lang, text, path, table.ToString());
            return document;
        }

        private string MakeHref(string url, string name)
        {
            return string.Format("<a href=\"{0}\">{1}</a>", url.Replace("file:", "file:///"), name);
        }
    }
}
